package com.yxw.yxnet_cd_center.customer_service.service.impl;

import com.yxw.yxnet_cd_center.customer_service.dto.NoticeQueryDTO;
import com.yxw.yxnet_cd_center.customer_service.dto.SendNoticeViewDTO;
import com.yxw.yxnet_cd_center.customer_service.dto.NoticeAddDTO;
import com.yxw.yxnet_cd_center.customer_service.dto.SendDelayNoticeDTO;
import com.yxw.yxnet_cd_center.customer_service.dto.SendNoticeSmsDTO;
import com.yxw.yxnet_cd_center.customer_service.dto.ChatRecordQueryDTO;
import com.yxw.yxnet_cd_center.customer_service.entity.YxCsNoticeEntity;
import com.yxw.yxnet_cd_center.customer_service.entity.YxcscClientFiledServiceEntity;
import com.yxw.yxnet_cd_center.customer_service.entity.YxCsSmsTemplateEntity;
import com.yxw.yxnet_cd_center.customer_service.entity.YxCsNoticeCircleEntity;
import com.yxw.yxnet_cd_center.customer_service.entity.YxCsNoticeSendEntity;
import com.yxw.yxnet_cd_center.customer_service.entity.YxCsWorkflowEntity;
import com.yxw.yxnet_cd_center.customer_service.mapper.WorkflowMapper;
import com.yxw.yxnet_cd_center.customer_service.mapper.YxcscClientFiledServiceMapper;
import com.yxw.yxnet_cd_center.customer_service.mapper.SmsTemplateMapper;
import com.yxw.yxnet_cd_center.customer_service.mapper.NoticeCircleMapper;
import com.yxw.yxnet_cd_center.customer_service.mapper.NoticeMapper;
import com.yxw.yxnet_cd_center.customer_service.utils.*;
import com.yxw.yxnet_cd_center.customer_service.vo.MqttInforSystemVO;
import com.yxw.yxnet_cd_center.customer_service.vo.DictionaryVo;
import com.yxw.yxnet_cd_center.customer_service.vo.MemberVo;
import com.yxw.yxnet_cd_center.customer_service.vo.YxCsNoticeVo;
import com.yxw.yxnet_cd_center.customer_service.vo.ChatRecordVo;
import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yxw.yxnet_cd_center.common.constant.CommonConstant;
import com.yxw.yxnet_cd_center.common.constant.MqttPrefixConstant;
import com.yxw.yxnet_cd_center.common.dto.HuaWeiSmsDTO;
import com.yxw.yxnet_cd_center.common.dto.PageVO;
import com.yxw.yxnet_cd_center.common.enums.NoticeTypeEnum;
import com.yxw.yxnet_cd_center.common.enums.SMSErrEnum;
import com.yxw.yxnet_cd_center.common.exception.BaseException;
import com.yxw.yxnet_cd_center.common.utils.BaseDateTime;
import com.yxw.yxnet_cd_center.customer_service.mqtt.MqttGateway;
import com.yxw.yxnet_cd_center.customer_service.service.DictService;
import com.yxw.yxnet_cd_center.customer_service.service.LogService;
import com.yxw.yxnet_cd_center.customer_service.service.NoticeCircleService;
import com.yxw.yxnet_cd_center.customer_service.service.NoticeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 消息设置
 * @author liuxin
 * @date 2023.09.15
 */
@Slf4j
@Service
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, YxCsNoticeEntity> implements NoticeService {

    @Autowired
    private NoticeMapper noticeMapper;

    @Autowired
    private UserUtil userUtil;

    @Autowired
    private DictService  dictService;

    @Autowired
    private MqttGateway mqttGateway;

    @Autowired
    private HuaWeiSmsUtil huaWeiSmsUtil;

    @Autowired
    private LogService logService;

    @Autowired
    private NoticeCircleService noticeCircleService;

    @Autowired
    private NoticeCircleMapper noticeCircleMapper;

    @Autowired
    private SmsTemplateMapper smsTemplateMapper;

    @Autowired
    private YxcscClientFiledServiceMapper clientFiledServiceMapper;

    @Autowired
    private WorkflowMapper workflowMapper;

    @Autowired
    private RedisManager redisManager;

    /**
     * 消息设置-消息通知列表查询
     * @param dto
     * @return
     */
    @Override
    public PageVO<YxCsNoticeVo> pageNoticeList(NoticeQueryDTO dto) {
        Page<YxCsNoticeEntity> page = new Page<>(dto.getCurrPage(), dto.getPageSize());
        LambdaQueryWrapper<YxCsNoticeEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .like(StringUtils.isNotBlank(dto.getProjectName()), YxCsNoticeEntity::getProjectName, StringUtil.trim(dto.getProjectName()))
                .eq(null!=dto.getSuitStatus(),YxCsNoticeEntity::getSuitStatus, dto.getSuitStatus())
                .eq(null!=dto.getProjectId(),YxCsNoticeEntity::getProjectId, dto.getProjectId())
                .eq(null!=dto.getStatus(),YxCsNoticeEntity::getStatus, dto.getStatus())
                .ge(StringUtils.isNotBlank(dto.getCreateTimeStart()), YxCsNoticeEntity::getCreateTime, BaseDateTime.getDate(dto.getCreateTimeStart()))
                .le(StringUtils.isNotBlank(dto.getCreateTimeEnd()), YxCsNoticeEntity::getCreateTime, BaseDateTime.getDate(dto.getCreateTimeEnd())).orderByDesc(YxCsNoticeEntity::getCreateTime);
        page = baseMapper.selectPage(page, queryWrapper);
        List<YxCsNoticeEntity> entityList = page.getRecords();
        List<YxCsNoticeVo> listVoList=new ArrayList<>();
        if(null!=entityList && !entityList.isEmpty()){
            listVoList = BeanUtil.copyToList(entityList, YxCsNoticeVo.class);
            //查询提醒方式
            for (int i = 0; i < listVoList.size(); i++) {
                YxCsNoticeVo noticeVo = listVoList.get(i);
                noticeVo.setNoticeWay(noticeMapper.getNoticeWayById(noticeVo.getId()));
            }
        }
        return PageUtils.get(page,listVoList);
    }

    /**
     * 消息设置-新增消息通知
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public YxCsNoticeVo addNotice(NoticeAddDTO dto) {
        //校验组名称不能重复
        LambdaQueryWrapper<YxCsNoticeEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(true,YxCsNoticeEntity::getProjectId,dto.getProjectId());
        YxCsNoticeEntity yxCsNoticeEntity = baseMapper.selectOne(queryWrapper);
        if(null!=yxCsNoticeEntity){
            throw  new BaseException("项目已存在,请重新选择项目");
        }
        Integer cycleFlag = dto.getCycleFlag();
        if(null!=cycleFlag && cycleFlag==1){
            Integer cycleFreq = dto.getCycleFreq();
            Integer cycleTime = dto.getCycleTime();
            if(null==cycleFreq || null==cycleTime){
                throw  new BaseException("提醒循环开启时,循环频次和循环时长不能为空");
            }
        }
        YxCsNoticeEntity entity = new YxCsNoticeEntity();
        BeanUtil.copyProperties(dto,entity);
        entity.setCreateId(userUtil.getLoginUserId());
        entity.setCreateName(userUtil.getLoginName());
        entity.setCreateTime(new Date());
        //项目名称
        DictionaryVo dicData = dictService.getDictDataById(dto.getProjectId());
        if(null!=dicData){
            entity.setProjectName(dicData.getName());
        }
        //提醒对象
        DictionaryVo objData = dictService.getDictDataById(dto.getNoticeObject());
        if(null!=objData){
            entity.setNoticeObjectName(objData.getName());
        }
        baseMapper.insert(entity);
        //新增提醒方式
        noticeMapper.addNoticeWay(entity.getId(),dto.getNoticeWay());
        YxCsNoticeVo vo = new YxCsNoticeVo();
        BeanUtil.copyProperties(entity,vo);
        return vo;
    }

    /**
     * 消息设置-消息通知详情
     * @param noticeId
     * @return
     */
    @Override
    public YxCsNoticeVo getNoticeInfoById(Long noticeId) {
        YxCsNoticeEntity entity = baseMapper.selectById(noticeId);
        YxCsNoticeVo vo = new YxCsNoticeVo();
        BeanUtil.copyProperties(entity,vo);
        //查询提醒方式
        List<Long> noticeWay=noticeMapper.getNoticeWayById(noticeId);
        vo.setNoticeWay(noticeWay);
        //查询提醒人
        List<MemberVo> userList =noticeMapper.getNoticeUserById(noticeId);
        vo.setUserList(userList);
        return vo;
    }

    /**
     * 消息设置-修改消息通知
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateNotice(NoticeAddDTO dto) {
        //校验组名称不能重复
        LambdaQueryWrapper<YxCsNoticeEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(true,YxCsNoticeEntity::getProjectId,dto.getProjectId()).ne(true,YxCsNoticeEntity::getId,dto.getId())
        .eq(true,YxCsNoticeEntity::getStatus,1);
        List<YxCsNoticeEntity> yxCsNoticeEntity = baseMapper.selectList(queryWrapper);
        if(null!=yxCsNoticeEntity  && !yxCsNoticeEntity.isEmpty()){
            throw  new BaseException("项目已存在,请重新选择项目");
        }
        if(null==dto.getId()){
            throw new BaseException("更新主键不能为空");
        }
        YxCsNoticeEntity entity = baseMapper.selectById(dto.getId());
        if(null==entity){
           throw new BaseException("未查询到需要更新的消息通知信息");
        }
        BeanUtil.copyProperties(dto,entity);
        entity.setUpdateId(userUtil.getLoginUserId());
        entity.setUpdateName(userUtil.getLoginName());
        entity.setUpdateTime(new Date());
        //项目名称
        DictionaryVo dicData = dictService.getDictDataById(dto.getProjectId());
        if(null!=dicData){
            entity.setProjectName(dicData.getName());
        }
        //提醒对象
        if(null!=dto.getNoticeObject()){
            if(1L==dto.getNoticeObject()){
                entity.setNoticeObjectName("关联员工");
            }else{
                entity.setNoticeObjectName("关联客户");
            }
        }
        //循环处理
        if(CommonConstant.ZERO==dto.getCycleFlag()){
            entity.setCycleFreq(null);
            entity.setCycleTime(null);
        }
        baseMapper.updateById(entity);
        //删除提方式
        noticeMapper.deleteNoticeWayById(dto.getId());
        //新增提醒方式
        noticeMapper.addNoticeWay(dto.getId(),dto.getNoticeWay());
    }

    /**
     * 删除消息通知
     * @param noticeId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteNoticeById(Long noticeId) {
        if(null==noticeId){
            throw new BaseException("删除主键不能为空");
        }
        //删除数据
        baseMapper.deleteById(noticeId);
    }

    /**
     * 消息通知状态修改
     * @param noticeId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStatusById(Long noticeId) {
        baseMapper.updateStatusById(noticeId);
    }


    /**
     * 消息设置-聊天记录列表统计
     * @param dto
     * @return
     */
    @Override
    public PageVO<ChatRecordVo> pageChatRecord(ChatRecordQueryDTO dto) {
        Page<ChatRecordVo> page = new Page<>(dto.getCurrPage(), dto.getPageSize());
        List<ChatRecordVo> recordLis=noticeMapper.getChatRecordList(page,dto);
        return PageUtils.get(page,recordLis);
    }

    /**
     * 消息提醒-短信发送
     */
    @Override
    @Async(value ="common-executor")
    public void sendNoticeToSms(SendNoticeSmsDTO dto){
        try {
            //校验必填参数
            this.validataToSms(dto);
            //查询模板信息
            LambdaQueryWrapper<YxCsSmsTemplateEntity> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(YxCsSmsTemplateEntity::getTemplateCode, dto.getNoticeType().getTemplateCode());
            YxCsSmsTemplateEntity entity = smsTemplateMapper.selectOne(wrapper);
            if(null==entity){
                throw new BaseException("短信模板未配置");
            }
            List<MemberVo> userList = dto.getUserList();
            //批量发送，每次发送300，小于华为云最大500条
            int totalSize = userList.size();
            int totalCnt = totalSize % 300 == 0 ? totalSize / 300 : totalSize / 300 + 1;
            for (int i = 0; i < totalCnt; i++) {
                try {
                    List<MemberVo> voList = userList.subList(i * 100, i == totalCnt - 1 ? totalSize : (i + 1 * 300));
                    //将电话号码过滤出来并使用','隔开进行批量发送
                    String phoneStr = voList.stream().map(vo -> vo.getPhone()).collect(Collectors.toList())
                            .stream().map(String::valueOf).collect(Collectors.joining(","));
                    //短信发送
                    HuaWeiSmsDTO smsto = new HuaWeiSmsDTO();
                    smsto.setTemplateParas(dto.getContent());
                    smsto.setPhone(phoneStr);
                    smsto.setTemplateId(entity.getHwTemplateId());
                    smsto.setSender(entity.getSender());
                    String body = huaWeiSmsUtil.sendSmsCode(smsto);
                    //解析保存数据
                    this.analysisBody(body, CommonConstant.ONE, userList,dto);
                } catch (Exception e) {
                    log.error("短信发送异常", e);
                    throw new BaseException(e.getMessage());
                }
            }
        }catch (Exception e){
            List<YxCsNoticeSendEntity> entityList = new ArrayList<>();
            YxCsNoticeSendEntity entity = new YxCsNoticeSendEntity();
            entity.setUserId(1L);
            entity.setUserName("系统");
            entity.setErrMsg("消息推送异常："+e.getMessage());
            entity.setBussId(dto.getBussId());
            entity.setStatus(CommonConstant.TWO);
            entity.setSendWay(CommonConstant.ONE);
            entity.setCreateTime(new Date());
            entityList.add(entity);
            //保存发送记录
            logService.saveNoticeSentLog(entityList);
        }
    }
    /**
     * 消息提醒-页面提醒发送
     */
    @Override
    @Async(value ="common-executor")
    public void sendNoticeToView(SendNoticeViewDTO dto){
        try {
            //校验必填参数
            this.validataToView(dto);
            //通知发送
            MqttInforSystemVO systemVO = new MqttInforSystemVO();
            systemVO.setContentType(dto.getContentType());
            systemVO.setMsgType("notification");
            systemVO.setContentType("text");
            List<YxCsNoticeSendEntity> entityList = new ArrayList<>();
            for (MemberVo user : dto.getUserList()) {
                systemVO.setRecv(String.valueOf(user.getId()));
                systemVO.setContent(dto.getContent());
                YxCsNoticeSendEntity entity = new YxCsNoticeSendEntity();
                try {
                    mqttGateway.sendToMqtt(MqttPrefixConstant.SYSTEM_SYSTEM_MQTT_TOPIC_PREFIX + user.getId(), JsonUtils.toJson(systemVO));
                    entity.setStatus(CommonConstant.ONE);
                } catch (Exception e) {
                    log.error("消息发送异常", e);
                    entity.setStatus(CommonConstant.TWO);
                    entity.setErrMsg(e.getMessage());
                }
                entity.setUserId(user.getId());
                entity.setUserName(user.getUserName());
                entity.setSendWay(CommonConstant.TWO);
                entity.setBussId(dto.getBussId());
                entityList.add(entity);
            }
            if(CommonConstant.ONE==dto.getCycleFlag()){
                //判断是否是循环提醒，如果是就放一条延迟队列数据用于二次接收发送（起一个定时器作用）
                noticeCircleService.saveNoticeCircle(dto);
                //放入消息提醒取消延迟列中
                mqttGateway.sendToMqtt(MqttPrefixConstant.MESSAGE_REMINDER_DELAY_TOPIC_PRODUCT.replace("XXX", String.valueOf(dto.getCycleFreq())) + dto.getBussId(),
                        CommonConstant.TWO, true, JsonUtils.toJson(dto));
            }
            if (!entityList.isEmpty()) {
                //保存发送记录
                logService.saveNoticeSentLog(entityList);
            }
        }catch (Exception e){
            List<YxCsNoticeSendEntity> entityList = new ArrayList<>();
            YxCsNoticeSendEntity entity = new YxCsNoticeSendEntity();
            entity.setUserId(1L);
            entity.setUserName("系统");
            entity.setErrMsg("消息推送异常："+e.getMessage());
            entity.setBussId(dto.getBussId());
            entity.setStatus(CommonConstant.TWO);
            entity.setSendWay(CommonConstant.TWO);
            entity.setCreateTime(new Date());
            entityList.add(entity);
            //保存发送记录
            logService.saveNoticeSentLog(entityList);
        }
    }

    /**
     * 轮询消息推送
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void pushCircleNoticeToView(SendNoticeViewDTO dto) {
        //查询轮询消息
        NoticeTypeEnum type = dto.getType();
        LambdaQueryWrapper<YxCsNoticeCircleEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(true,YxCsNoticeCircleEntity::getBussId,dto.getBussId())
                .eq(true,YxCsNoticeCircleEntity::getNoticeType,type.getCodeType());
        YxCsNoticeCircleEntity entity = noticeCircleMapper.selectOne(queryWrapper);
        //消息不存在说明已经处理了不再推送
        if(null==entity || CommonConstant.ONE== entity.getStatus() || CommonConstant.TWO== entity.getStatus()){
            return;
        }
        //继续推送消息
        this.sendNoticeToView(dto);
        //修改推送次数
        entity.setExecNum(entity.getExecNum()+1);
        if(entity.getExecNum()>=entity.getTotalNum()){
            entity.setStatus(CommonConstant.TWO);
            entity.setFinishTime(new Date());
        }
        noticeCircleMapper.updateById(entity);
    }

    /**
     *轮询消息处理取消推送接口
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelNoticeToView(SendNoticeViewDTO dto) {
        Object o = redisManager.get(MqttPrefixConstant.MESSAGE_REMINDER_DELAY_TOPIC_CONSUMER + dto.getBussId() + "_" + dto.getType().getCodeType());
        if(null!=o){
            return;
        }
        //查询轮询消息
        NoticeTypeEnum type = dto.getType();
        LambdaQueryWrapper<YxCsNoticeCircleEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(true,YxCsNoticeCircleEntity::getBussId,dto.getBussId())
                .eq(true,YxCsNoticeCircleEntity::getNoticeType,type.getCodeType())
                .eq(true,YxCsNoticeCircleEntity::getStatus,0);
        YxCsNoticeCircleEntity entity = noticeCircleMapper.selectOne(queryWrapper);
        if(null!=entity){
            entity.setStatus(CommonConstant.ONE);
            entity.setFinishTime(new Date());
            noticeCircleMapper.updateById(entity);
        }
        //终止过的消息就存入redis，减少二次终止
        redisManager.set(MqttPrefixConstant.MESSAGE_REMINDER_DELAY_TOPIC_CONSUMER+dto.getBussId()+"_"+dto.getType().getCodeType(),dto,24 * 60 * 60);
    }

    /**
     * 3分钟未处理消息推送
     * @param dto
     */
    @Override
    public void delayReminderScenario(SendDelayNoticeDTO dto) {
        if(null==dto.getBussId() || null==dto.getType()){
            throw new BaseException("业务对象/消息类型不能为空");
        }
        String noticeType = dto.getType().getCodeType();
        YxCsNoticeEntity noticeEntity=noticeMapper.getNoticeByType(dto.getType().getCodeType());
        //未配置就不发送
        if(null==noticeEntity){
            throw new BaseException(dto.getType().getTemplateName()+"未配置模板！");
        }
        //客户来访通知
        if("1".equals(noticeType)){
            //查询来访通知是否接单,已结单就不在通知
            LambdaQueryWrapper<YxcscClientFiledServiceEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(true,YxcscClientFiledServiceEntity::getId,dto.getBussId())
                    .eq(true,YxcscClientFiledServiceEntity::getState,CommonConstant.TWO);
            YxcscClientFiledServiceEntity entity = clientFiledServiceMapper.selectOne(queryWrapper);
            //三分钟未处理，就按配置消息通知信息来进行消息通知
            this.sendDelayNotice(dto, noticeEntity,entity);
        }
        //客户消息回复通知
        else if("2".equals(noticeType)){
            //由于服务未处理场景太多,就默认一个会话只提醒一次
            LambdaQueryWrapper<YxCsNoticeCircleEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(true,YxCsNoticeCircleEntity::getBussId,dto.getBussId())
                    .eq(true,YxCsNoticeCircleEntity::getNoticeType,dto.getType().getCodeType());
            YxCsNoticeCircleEntity entity = noticeCircleMapper.selectOne(queryWrapper);
            //三分钟未处理，就按配置消息通知信息来进行消息通知
            this.sendDelayNotice(dto, noticeEntity,entity);
        }
        //工作组转接通知
        else if("5".equals(noticeType)){
            //查询工作流是否
            LambdaQueryWrapper<YxCsWorkflowEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(true,YxCsWorkflowEntity::getId,dto.getBussId())
                    .eq(true,YxCsWorkflowEntity::getEndFlag,CommonConstant.ZERO);
            YxCsWorkflowEntity entity = workflowMapper.selectOne(queryWrapper);
            //三分钟未处理，就按配置消息通知信息来进行消息通知
            this.sendDelayNotice(dto,noticeEntity,entity);
        }
    }

    /**
     * 抽取客服接待客户数统计
     */
    @Override
    public void execChatStatistics() {
        //先删除
        noticeMapper.deleteChatRecord();
        //新增
        noticeMapper.addChatRecord();
    }


    //----------------------------------------------------------------------------------------------------------------------------------------
    /**
     * 延迟提醒信息发送
     */
    private void sendDelayNotice(SendDelayNoticeDTO dto,YxCsNoticeEntity noticeEntity,Object entity){
        //业务被处理以后就修改循环记录为已处理然后不再循环
        if(null==entity){
            LambdaQueryWrapper<YxCsNoticeCircleEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(true,YxCsNoticeCircleEntity::getBussId,dto.getBussId());
            YxCsNoticeCircleEntity NoticeCircleEntity = noticeCircleMapper.selectOne(queryWrapper);
            if(null!=NoticeCircleEntity){
                NoticeCircleEntity.setFinishTime(new Date());
                NoticeCircleEntity.setStatus(1);
                noticeCircleMapper.updateById(NoticeCircleEntity);
            }
            log.info("三分钟延迟发送消息任务终止，消息业务bussId参数：{}", dto.getBussId());
            return;
        }
        //查询提醒方式
        List<Long> noticeWays = noticeMapper.getNoticeWayById(noticeEntity.getId());
        for (Long noticeWay :noticeWays) {
            if(noticeWay==1L){
                //调用短信提醒方式
                SendNoticeSmsDTO smsDto = new SendNoticeSmsDTO();
                //组装消息发送信息
                smsDto.setBussId(dto.getBussId());
                smsDto.setNoticeType(dto.getType());
                smsDto.setUserList(dto.getUserList());
                this.sendNoticeToSms(smsDto);
            }else{
                SendNoticeViewDTO viewDto = new SendNoticeViewDTO();
                BeanUtil.copyProperties(dto,viewDto);
                //组装消息发送信息
                viewDto.setContent(noticeEntity.getNoticeDec());
                viewDto.setCycleFlag(noticeEntity.getCycleFlag());
                viewDto.setCycleFreq(noticeEntity.getCycleFreq());
                viewDto.setCycleTime(noticeEntity.getCycleTime());
                viewDto.setType(dto.getType());
                viewDto.setUserList(dto.getUserList());
                //调用页面声音提醒方式
                this.sendNoticeToView(viewDto);
            }
        }
    }
    /**
     * 解析返回结果
     */
    private void analysisBody(String body,Integer sendWay,List<MemberVo> userList,SendNoticeSmsDTO dto) throws JsonProcessingException {
        Map bodyMap = JSON.parseObject(body, Map.class);
        String code=String.valueOf(bodyMap.get("code"));
        List<YxCsNoticeSendEntity> entityList=new ArrayList<>();
        if(StringUtils.isNotBlank(code)){
                if(SMSErrEnum.SUCCESS.getCode().equals(code)){
                    //全部成功
                    for (MemberVo user:userList) {
                        YxCsNoticeSendEntity entity = new YxCsNoticeSendEntity();
                        //发送记录数据组装
                        entity.setSendWay(sendWay);
                        entity.setUserId(user.getId());
                        entity.setUserName(user.getUserName());
                        entity.setStatus(CommonConstant.ONE);
                        entity.setBussId(dto.getBussId());
                        entityList.add(entity);
                    }
                }else{
                    //result节点可能是空的，所以需要进行判断
                    String resultJson =String.valueOf(bodyMap.get("result"));
                    //解析result节点进行单个判断
                    ObjectMapper mapper = new ObjectMapper();
                    List<Map<String,String>> resultMapList = mapper.readValue(resultJson, new TypeReference<List<Map<String,String>>>(){});
                    if(null!=resultMapList && !resultMapList.isEmpty()){
                        for (int i = 0; i <userList.size() ; i++) {
                            YxCsNoticeSendEntity entity = new YxCsNoticeSendEntity();
                            MemberVo user = userList.get(i);
                            //通过电话号码过滤返回信息
                            List<Map<String,String>> mapList = resultMapList.stream().filter(resultMap -> resultMap.get("originTo").equals(user.getPhone())).collect(Collectors.toList());
                            //状态：0000为发送成功
                            String status="";
                            if(null!=mapList && !mapList.isEmpty()){
                                status =(mapList.get(0).get("status"));
                            }
                           if(SMSErrEnum.SUCCESS.getCode().equals(status)){
                                entity.setStatus(CommonConstant.ONE);
                            }else{
                                entity.setStatus(CommonConstant.TWO);
                                entity.setErrMsg(status+":"+ SMSErrEnum.getErrMsgByCode(status));
                            }
                            //发送记录数据组装
                            entity.setBussId(dto.getBussId());
                            entity.setSendWay(sendWay);
                            entity.setUserId(user.getId());
                            entity.setUserName(user.getUserName());
                            entityList.add(entity);
                        }
                    }else{
                        //返回节点为空时,就取description异常信息进行保存
                        for (int i = 0; i <userList.size() ; i++) {
                            YxCsNoticeSendEntity entity = new YxCsNoticeSendEntity();
                            MemberVo user = userList.get(i);
                            entity.setStatus(CommonConstant.TWO);
                            entity.setErrMsg("问题【："+SMSErrEnum.getErrMsgByCode(String.valueOf(bodyMap.get("code")))+"】;解决方法【"+SMSErrEnum.getDealMethodByCode(String.valueOf(bodyMap.get("code")))+"】");
                            //发送记录数据组装
                            entity.setSendWay(sendWay);
                            entity.setUserId(user.getId());
                            entity.setUserName(user.getUserName());
                            entity.setBussId(dto.getBussId());
                            entityList.add(entity);
                        }
                    }
                }
        }else{
            throw new BaseException("短信发送返回报文异常！");
        }
        if(!entityList.isEmpty()){
            //保存发送记录
            logService.saveNoticeSentLog(entityList);
        }
    }

    /**
     * 消息发送校验必填-页面
     * @param dto
     */
    private void validataToView(SendNoticeViewDTO dto) {
        StringBuffer sbf=new StringBuffer();
        if(null==dto){
            throw new BaseException("提醒消息实体不能为空!");
        }
        if(null==dto.getBussId()){
            sbf.append("消息对应业务ID不能为空!");
        }
        if(null==dto.getCycleFlag()){
            sbf.append("是否循环提醒不能为空!");
        }else{
            if(CommonConstant.ONE==dto.getCycleFlag()){
                if(null==dto.getCycleFreq() ||null==dto.getCycleTime()){
                    sbf.append("循环提醒频次／循环时常不能为空!");
                }
            }
        }
        if(StringUtils.isBlank(dto.getContent())){
            sbf.append("提醒内容不能为空!");
        }
        if(null==dto.getType()){
            sbf.append("提醒消息类型不能为空!");
        }
        if(null==dto.getUserList() || dto.getUserList().isEmpty()){
            sbf.append("提醒人员不能为空!");
        }else{
            for (MemberVo user :dto.getUserList()) {
                Long userId = user.getId();
                String userName = user.getUserName();
                if( StringUtils.isBlank(userName) || null==userId){
                    sbf.append("发送人员ID/名字不能为空!");
                    break;
                }
            }
        }
        if(StringUtils.isNotBlank(sbf)){
            throw new BaseException("发送提醒消息失败："+sbf.toString());
        }
    }

    /**
     * 消息发送校验必填-短信
     * @param dto
     */
    private void validataToSms(SendNoticeSmsDTO dto) {
        StringBuffer sbf=new StringBuffer();
        if(null==dto){
            throw new BaseException("提醒消息实体不能为空!");
        }
        if(null==dto.getBussId()){
            sbf.append("消息对应业务ID不能为空!");
        }
        if(null==dto.getUserList() || dto.getUserList().isEmpty()){
            sbf.append("提醒人员不能为空!");
        }else{
            for (MemberVo user :dto.getUserList()) {
                String phone = user.getPhone();
                Long userId = user.getId();
                String userName = user.getUserName();
                if(StringUtils.isBlank(phone) || StringUtils.isBlank(userName) || null==userId){
                    sbf.append("发送人员电话/ID/名字不能为空!");
                    break;
                }
            }
        }
        if(null==dto.getNoticeType()){
            sbf.append("消息类型不能为空!");
        }
        if(StringUtils.isNotBlank(sbf)){
            throw new BaseException("发送提醒消息失败："+sbf.toString());
        }
    }
}
